package role

import (
	"context"
	"fmt"
	"net/http"
	"wms/model"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ApiDistributeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewApiDistributeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ApiDistributeLogic {
	return &ApiDistributeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ApiDistributeLogic) ApiDistribute(req *types.RoleApisRequest) (resp *types.BaseResponse, err error) {
	resp = new(types.BaseResponse)

	//角色权限写入casbin
	//1.角色是否存在
	_, err = l.svcCtx.RoleModel.FindOne(l.ctx, req.RoleId)
	switch err {
	case nil:
	case model.ErrNotFound:
		fmt.Printf("[Error]角色[%d]不存在\n", req.RoleId)
		resp.Code = http.StatusBadRequest
		resp.Msg = "角色不存在"
		return resp, nil
	default:
		fmt.Printf("[Error]查询角色[%d]:%s\n", req.RoleId, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//2.查询分配的api是否存在
	var apis = make([]model.Api, 0)
	for _, apiId := range req.ApisId {
		var one *model.Api
		one, err = l.svcCtx.ApiModel.FindOne(l.ctx, apiId)
		switch err {
		case nil:
			apis = append(apis, *one)
		case model.ErrNotFound:
			fmt.Printf("[Error]api[%d]不存在\n", apiId)
			resp.Code = http.StatusBadRequest
			resp.Msg = "部分api不存在"
			return resp, nil
		default:
			fmt.Printf("[Error]查询api[%d]:%s\n", apiId, err.Error())
			resp.Code = http.StatusInternalServerError
			resp.Msg = "服务内部错误"
			return resp, nil
		}
	}

	//2.删除角色的权限
	_, err = l.svcCtx.Enforcer.DeletePermissionsForUser(fmt.Sprintf("role_%d", req.RoleId))
	if err != nil {
		fmt.Printf("[Error]删除角色[%d]的权限:%s\n", req.RoleId, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//3.角色添加权限
	var permissions [][]string
	for _, api := range apis {
		//3.1 角色添加api[role_menu]
		if api.Type == 1 || api.Uri == "" {
			continue
		}

		//permissions = append(permissions, []string{fmt.Sprintf("role_%d", req.RoleId), fmt.Sprintf("api_%d", api.Id), "X"})
		permissions = append(permissions, []string{fmt.Sprintf("role_%d", req.RoleId), api.Uri, api.Method})
	}

	fmt.Println("待添加权限：", permissions)
	if len(permissions) > 0 {
		_, err = l.svcCtx.Enforcer.AddPolicies(permissions)
		if err != nil {
			fmt.Printf("[Error]角色[%d]添加权限:%s\n", req.RoleId, err.Error())
			resp.Code = http.StatusInternalServerError
			resp.Msg = "服务内部错误"
			return resp, nil
		}
	}

	if err = l.svcCtx.Enforcer.SavePolicy(); err != nil {
		fmt.Printf("[Error]角色[%d]保存权限:%s\n", req.RoleId, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"
	return resp, nil
}
